﻿using ChineseAreaService;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Newtonsoft.Json;
using Sino.CapacityCloud.Services.Models;
using Sino.WebApi.Framework.Client;
using Sino.WebApi.Framework.Primitives;
using Sino.WebApi.Framework.Protocol;
using Sino.WebApi.Framework.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Services
{

    public class ServiceBusRepeater
        : TokenBasedWebApiClient, IServiceBusRepeater
    {

        #region Constants
        /// <summary>Geive 10 times for retrying to recover from access_token_timeout.</summary>
        public const uint DefaultAccessTimeoutRetries = 10;

        public const string PublishUrl = "Publish?typeName={0}";
        #endregion

        #region Fields
        protected readonly ILogger _logger;

        protected readonly IChinaAreaService _areaService;
        #endregion

        #region Properties
        public override TimeSpan DefaultTimeout
        {
            get
            {
                return TimeSpan.FromMilliseconds(-1);
            }
        }
        #endregion

        #region Constructors
        public ServiceBusRepeater(IHostingEnvironment env, ILoggerFactory loggerFactory, IChinaAreaService areaService)
            : this(LoadSettings(env, "Data:DefaultConnection:ServiceBusRepeater"))
        {
            this._areaService = areaService;
            this._logger = loggerFactory.CreateLogger<TmsServiceBus>();
            this.Initialize();
        }

        protected ServiceBusRepeater(IOptions<TmsServiceBusOptions> options)
           : base(options.Value.BaseUrl, options.Value.AppId, options.Value.AppSecrect, options.Value.AccessTimeoutRetries)
        {
        }

        protected ServiceBusRepeater(TmsServiceBusOptions options)
            : base(options.BaseUrl, options.AppId, options.AppSecrect, options.AccessTimeoutRetries)
        {
        }

        protected ServiceBusRepeater(string baseUrl, string appId, string appSecrect, uint accessTimeoutRetries = DefaultAccessTimeoutRetries)
            : base(baseUrl, appId, appSecrect, accessTimeoutRetries)
        {
        }

        /// <summary>
        /// Finalizer for the TmsServiceBus.
        /// </summary>
        ~ServiceBusRepeater()
        {
            Dispose(false);
        }

        public override bool Initialize()
        {
            var r = base.Initialize();
            this.AuthorizeAsync();
            return r;
        }
        #endregion

        #region Web API
        public async Task<VoidResponse> PublishAsync(string typeName, object eventData)
        {
            this._logger.LogInformation($"Calling PublishAsync: typeName = {typeName}.");
            return await this.InvokeWebApiByConventionAsync<VoidResponse>(async (finalUrl, ct) =>
            {
                var json = JsonConvert.SerializeObject(eventData);
                return await this._client.PostAsync(finalUrl, new StringContent(json, Encoding.UTF8, "application/json"));
            }, new { typeName = typeName });
        }
        #endregion

        #region Utilities
        protected override void OnError(object sender, string message, Exception ex, object tag = null)
        {
            if (ex != null && (ex is AccessTokenTimeoutException || ex.InnerException is AccessTokenTimeoutException))
            {
                var token = this.AuthorizeAsync().GetAwaiter().GetResult();
                this._logger.LogError($"{sender.GetType().FullName}: {message}\r\n{token}", ex);
            }
            else
            {
                this._logger.LogError($"{sender.GetType().FullName}: {message}\r\n{tag?.ToString()}", ex);
            }
        }

        protected static TmsServiceBusOptions LoadSettings(IHostingEnvironment env, string sectionName, string configurationFileName = "appsettings")
        {
            var configurationBuilder = new ConfigurationBuilder()
                .AddJsonFile($"{configurationFileName}.json")
                .AddJsonFile($"{configurationFileName}.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            var configuration = configurationBuilder.Build().GetSection(sectionName);

            return new TmsServiceBusOptions(configuration["BaseUrl"], configuration["AppKey"], configuration["AppSecret"], uint.Parse(configuration["AccessTimeoutRetries"]));
        }
        #endregion

        #region IDisposable
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
        #endregion

        #region Internals
        #endregion

    }

}